package com.jieshuibao.service;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.jieshuibao.common.config.Global;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.domain.SmsBean;
import com.jieshuibao.util.StringUtils;

@Service
public class ChangeCodeService {
	
	@Resource
	private RedisService redisService;
	public Map<String, String> checkSms(String smsMessageSid,String code){
		Map<String,String> map = new HashMap<String, String>();
		if(StringUtils.isEmpty(smsMessageSid)){
			map.put("code", Global.SYSTEMERROR);
			map.put("des", "系统繁忙！");
			return map;
		}
		try {
			SmsBean smsBean = redisService.getObejct(smsMessageSid,SmsBean.class);
			if(null == smsBean){
				map.put("code", Global.FAIL);
				map.put("des", "验证码失效");
				return map;
			}
			int n = smsBean.getErrorCount();
			if(smsBean.getCode().equalsIgnoreCase(code)){
				map.put("code", Global.SUCCESS);
				map.put("des", "验证码正确");
				redisService.delete(smsMessageSid);
				return map;
			}else{
				n++;
				if(n>3){
					redisService.delete(smsMessageSid);
					map.put("code", Global.FAIL);
					map.put("des", "验证码失效");
					return map;
				}
				smsBean.setErrorCount(n);
				redisService.setObject(smsMessageSid, smsBean);
				map.put("code", Global.FAIL);
				map.put("des", "验证码错误");
				return map;
			}
		} catch (Exception e) {
		
			map.put("code", Global.SYSTEMERROR);
			map.put("des", "系统繁忙");
			return map;
		}

	}
	public Map<String, String> checkSmsApp(String smsMessageSid,String code,String phone){
		Map<String,String> map = new HashMap<String, String>();
		if(StringUtils.isEmpty(smsMessageSid)){
			map.put("code", "0");
			map.put("des", "参数短信key错误！");
			return map;
		}
		try {
			SmsBean smsBean = redisService.getObejct(smsMessageSid,SmsBean.class);
			if(null == smsBean){
				map.put("code", "3");
				map.put("des", "验证码失效");
				return map;
			}
			int n = smsBean.getErrorCount();
			if(smsBean.getCode().equalsIgnoreCase(code)){
				String phone2 = smsBean.getPhone();
				if(phone2.equals(phone)){
					map.put("code", BaseRes.SUCCESS_CODE);
					map.put("des", "验证码正确");
					redisService.delete(smsMessageSid);
					return map;
				}else {
					map.put("code", BaseRes.FAIL_CODE);
					map.put("des", "手机号与您获取验证码的手机号不一致！");
					return map;
				}
			}else{
				n++;
				if(n>3){
					redisService.delete(smsMessageSid);
					map.put("code", "3");
					map.put("des", "验证码失效");
					return map;
				}
				smsBean.setErrorCount(n);
				redisService.setObject(smsMessageSid, smsBean);
				map.put("code", "3");
				map.put("des", "验证码错误");
				return map;
			}
		} catch (Exception e) {
		
			map.put("code", "0");
			map.put("des", "系统繁忙");
			return map;
		}

	}
}
